const crypto = require('crypto');
const { ipcRenderer } = require('electron');

/**
 * 计算文件MD5
 */
async function calculateFileMD5(filePath) {
  const buffer = await ipcRenderer.invoke('read-file', filePath);
  const hash = crypto.createHash('md5');
  hash.update(buffer);
  return hash.digest('hex');
}

/**
 * 检查文件是否已存在（根据MD5）
 */
async function checkFileExists(fileName, md5Hash, token) {
  const response = await fetch(`${SERVER_URL}/api/files/check-exists`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({ fileName, md5: md5Hash })
  });
  
  const result = await response.json();
  return result.exists;
}

/**
 * 秒传功能（文件已存在则直接引用）
 */
async function quickUpload(fileName, md5Hash, fileSize, parentPath, token) {
  const response = await fetch(`${SERVER_URL}/api/files/quick-upload`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      fileName,
      md5: md5Hash,
      fileSize,
      parentPath
    })
  });
  
  return await response.json();
}

module.exports = {
  calculateFileMD5,
  checkFileExists,
  quickUpload
};

